<template>
  <el-form
    ref="form"
    :model="formData"
    :rules="rules"
    label-width="0"
    class="form"
  >
    <el-table
      :data="formData.dataList"
      style="width: 100%"
      border
      :header-cell-style="tableTopStyle"
    >
      <el-table-column width="400">
        <template slot="header">
          <span class="xing">规格名称</span>
        </template>
        <template slot-scope="{ row, $index }">
          <el-form-item
            :prop="`dataList.${$index}.spu_name`"
            :rules="rules.spu_name"
          >
            <div class="icon">
              <i class="vxe-icon-square-plus" @click="plus"></i>
              <!-- 添加的减 -->
              <i
                class="vxe-icon-square-minus"
                @click="reduce($index)"
                v-if="$index != 0 && !id"
              ></i>
              <!-- 编辑的减 -->
              <i
                class="vxe-icon-square-minus"
                @click.stop="row.id ? reduces($index, 2) : reduces($index)"
                v-if="$index != 0 && id"
              ></i>
            </div>
            <!-- 添加 -->
            <el-autocomplete
              :disabled="row.standard_spu_id ? show : false"
              v-model="row.spu_name_title"
              ref="searchSelect"
              class="wid140"
              @clear="clearData(row, $index, 1)"
              :fetch-suggestions="!transfer ? querySearchAsync : spuSearchAsync"
              placeholder="选择规格"
              clearable
              @select="
                (item) => {
                  handleSelect(item, row, $index, 1);
                }
              "
              v-if="!id"
            >
            </el-autocomplete>
            <!-- 编辑 -->
            <el-autocomplete
              v-else
              :disabled="
                (row.standard_spu_id ? show : false) ||
                (row.is_update == 'no' && $index == 0)
              "
              v-model="row.spu_title"
              ref="searchSelect"
              class="wid140"
              @clear="clearData(row, 1)"
              :fetch-suggestions="!transfer ? querySearchAsync : spuSearchAsync"
              placeholder="规格"
              clearable
              @select="
                (item) => {
                  handleSelect(item, row, $index, 1);
                }
              "
            >
            </el-autocomplete>
            <div class="span" v-if="row.base == 1" style="margin-left: 5px">
              基础单位
            </div>
            <div v-else class="flex-middle" style="margin-left: 5px">
              <span class="span">= </span>
              <el-input
                v-model="row.package_num"
                class="wid80"
                style="margin: 0 4px"
                placeholder="互调比"
                clearable
                :disabled="row.is_update == 'no'"
                @input="changePrice(row, 'package_num')"
              ></el-input>
              <span
                class="span spuunit"
                :title="
                  id
                    ? formData.dataList[0].spu_title
                    : formData.dataList[0].spu_name_title
                "
                >{{
                  id
                    ? formData.dataList[0].spu_title
                    : formData.dataList[0].spu_name_title
                }}</span
              >
              <span class="bundle"
                >{{ dundlePirce(row.market_price, row.package_num) }}元/{{
                  id
                    ? formData.dataList[0].spu_title
                    : formData.dataList[0].spu_name_title
                }}</span
              >
            </div>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column width="130">
        <template slot="header">
          <span class="xing">单位</span>
        </template>
        <template slot-scope="{ row, $index }">
          <el-form-item :prop="`dataList.${$index}.unit`" :rules="rules.unit">
            <template v-if="transfer">
              <el-input
                :disabled="true"
                class="wid100"
                v-model="row.spu_name_title"
                placeholder="单位"
                clearable
                v-if="!id"
              >
              </el-input>
              <el-input
                v-else
                :disabled="true"
                class="wid100"
                v-model="row.spu_title"
                placeholder="单位"
                clearable
              >
              </el-input>
            </template>
            <template v-else>
              <el-autocomplete
                v-if="!id"
                :disabled="row.standard_spu_id ? show : false"
                v-model="row.unit_name"
                ref="unitSelect"
                class="wid100"
                @clear="clearData(row, $index, 2)"
                :fetch-suggestions="unitSearchAsync"
                placeholder="单位"
                clearable
                @select="
                  (item) => {
                    handleSelect(item, row, $index, 2);
                  }
                "
              >
              </el-autocomplete>
              <el-autocomplete
                v-else
                :disabled="row.standard_spu_id ? show : false"
                v-model="row.spu_unit"
                ref="unitSelect"
                class="wid_237"
                @clear="clearData(row, 2)"
                :fetch-suggestions="unitSearchAsync"
                placeholder="单位"
                clearable
                @select="
                  (item) => {
                    handleSelect(item, row, $index, 2);
                  }
                "
              >
              </el-autocomplete>
            </template>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="描述" width="160">
        <template slot-scope="{ row }">
          <el-form-item>
            <el-input
              class="wid140"
              v-model="row.describe"
              placeholder="描述"
              clearable
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="编码SKU" width="130">
        <template slot-scope="{ row }">
          <el-form-item>
            <el-input
              v-model="row.goods_spu_code"
              class="wid100"
              placeholder="编码SKU"
              clearable
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column width="130">
        <template slot="header">
          <span class="xing">采购价</span>
        </template>
        <template slot-scope="{ row, $index }">
          <el-form-item
            :prop="'dataList.' + $index + '.purchase_price'"
            :rules="rules.purchase_price"
          >
            <el-input
              v-model="row.purchase_price"
              class="wid100"
              placeholder="采购价"
              @input="changePrice(row, 'purchase_price')"
              clearable
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column width="130">
        <template slot="header">
          <span class="xing">市场价</span>
        </template>
        <template slot-scope="{ row, $index }">
          <el-form-item
            :prop="'dataList.' + $index + '.market_price'"
            :rules="rules.market_price"
          >
            <el-input
              v-model="row.market_price"
              class="wid100"
              placeholder="市场价"
              @input="changePrice(row, 'market_price')"
              clearable
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="起订量" width="130">
        <template slot-scope="{ row }">
          <el-form-item>
            <el-input
              v-model="row.minimum"
              class="wid100"
              placeholder="起订量"
              clearable
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="损耗率" width="130">
        <template slot-scope="{ row }">
          <el-form-item>
            <el-input
              v-model="row.attrition_rate"
              class="wid100"
              placeholder="损耗率"
              clearable
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="库存设置" width="240">
        <template slot-scope="{ row, $index }">
          <el-form-item>
            <el-select
              v-model="row.demo_designated_inventory"
              placeholder="请选择"
              @change="edit_inventory(row)"
              class="wid120"
              :disabled="transfer == 1 && Boolean($index)"
            >
              <el-option
                v-for="item in inventoryOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-input
              class="wid100"
              style="margin-left: 5px"
              v-if="row.demo_designated_inventory != -1"
              :disabled="
                row.demo_designated_inventory != 1 || (transfer == 1 && Boolean($index))
              "
              @blur="blur_input"
              onkeyup="value=value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
              v-model="row.designated_inventory"
              placeholder="库存"
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="{ row, $index }">
          <el-form-item
            :prop="'dataList.' + $index + '.status'"
            :rules="rules.status"
          >
            <el-switch
              v-model="row.status"
              active-color="#03A98E"
              active-text="开"
              inactive-text="关"
              class="mainor_switch"
            ></el-switch>
          </el-form-item>
        </template>
      </el-table-column>
    </el-table>
    <div class="note">
      注意事项 <i class="el-icon-warning-outline"></i>：
      1.多单位商品仅用基础单位进行库存管理时，建议勾选【分拣按基础单位】2.
      多单位商品每个单位库存独立管理时，不建议勾选按【分拣按基础单位】3.
      辅助单位转换系数和基础单位设定后，生成采购单或订单后不支持修改
    </div>
  </el-form>
</template>

<script>
import { goods_delete } from "@/api/commodity/commodityList";
import { packApi } from "@/utils/public";
import { debounce } from "@/utils/debounce";
const list = {
  spu_title: "",
  spu_unit: "",
  base: 0,
  spu_name: "",
  unit: "",
  package_num: 1,
  transfer_unit: "",
  transfer_num: 0,
  is_float: true,
  standard_spu_id: 0,
  standard_spu_code: "",
  down: false,
  goods_spu_code: "",
  market_price: "",
  purchase_price: "",
  minimum: "",
  attrition_rate: "",
  status: true,
  exp: "",
  madein: "",
  designated_inventory: 0,
  demo_designated_inventory: 0,
};
export default {
  props: {
    rules: Object,
    show: Boolean,
    transfer: {
      type: Boolean,
      default: false,
    },
    info: Object,
    id: {
      type: [String, Number],
      default: "",
    },
    purchase_unit:{
      type: [String, Number],
      default: "",
    }
  },
  watch: {
    "formData.dataList": {
      handler(val) {
        this.$emit("changeList", val);
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      tableTopStyle: { background: "#f6f8f9", color: "#181818" },
      formData: {
        dataList: [
          {
            spu_name_title: "", // 规格
            unit_name: "", // 单位
            describe: "", // 描述
            base: 1, // 为1的是基础
            spu_name: "", // 规定id
            unit: "",
            package_num: 1, // 互调比
            transfer_unit: "", // 没有用到
            transfer_num: 0, // 没有用到
            is_float: true, // 没有用到
            standard_spu_id: 0, // 没有用到
            standard_spu_code: "", // 没有用到
            down: false, // 没有用到
            goods_spu_code: "", // 编码SKU
            market_price: "", // 市场价
            purchase_price: "", // 采购价
            minimum: "", // 起订量
            attrition_rate: "", // 损耗率
            status: true, // 状态
            designated_inventory: 0, // 库存设置
            demo_designated_inventory: 0, // 库存设置下拉框
          },
        ],
      },
      // 库存设置下拉框
      inventoryOption: [
        {
          value: 0,
          label: "不指定库存",
        },
        {
          value: -1,
          label: "指定实际库存",
        },
        {
          value: 1,
          label: "自定义库存",
        },
      ],
      inlist: [
        {
          spu_title: "",
          spu_unit: "",
          base: 1,
          spu_name: "",
          unit: "",
          package_num: 1,
          transfer_unit: "",
          transfer_num: 0,
          is_float: true,
          standard_spu_id: 0,
          standard_spu_code: "",
          down: false,
          goods_spu_code: "",
          market_price: "",
          purchase_price: "",
          minimum: "",
          attrition_rate: "",
          status: true,
          designated_inventory: 0,
          demo_designated_inventory: 0,
        },
      ],
    };
  },
  methods: {
    /**
     * 清除规格和单位事件
     * @param {Object} item - 下拉框选中的只
     * @param {Object} row - 当前处理的表格行数据
     * @param {Number} index - 表格行的索引
     * @param {Number} type - 标识是规格（1）还是单位（非1）
     * @description
     * 根据`this.transfer`的值判断是否可互调。
     * 进行相应字段的赋值
     */
    //规格和单位选择
    handleSelect(item, row, index, type) {
      if (type == 1) {
        if (this.transfer == 1) {
          this.$set(row, "unit", item.id);
          this.$set(row, "spu_name", item.id);
          this.$set(row, "spu_name_title", item.title);
          this.$set(this.formData.dataList, index, row);
          let item_str = "dataList." + index + ".spu_name";
          let str = "dataList." + index + ".unit";
          this.$refs["form"].clearValidate(item_str);
          this.$refs["form"].clearValidate(str);
        } else {
          this.$set(row, "spu_name", item.id);
          this.$set(row, "spu_name_title", item.title);
          this.$set(this.formData.dataList, index, row);
          let item_str = "dataList." + index + ".spu_name";
          this.$refs["form"].clearValidate(item_str);
        }
      } else {
        row.unit_name = item.title;
        row.unit = item.id;
        this.$set(this.formData.dataList, index, row);
        let item_unit = "dataList." + index + ".unit";
        this.$refs["form"].clearValidate(item_unit);
      }
    },
    /**
     * 清除规格和单位事件
     * @param {Object} row - 当前处理的表格行数据
     * @param {Number} index - 表格行的索引
     * @param {Number} type - 标识是规格（1）还是单位（非1）
     * @description
     * 根据是否处于编辑模式（由`this.id`决定），函数会执行不同的清除逻辑。
     * 如果处于编辑模式，根据`this.transfer`的值，会有不同的字段清除策略。
     * 如果处于添加模式，根据`type`的值，会清除相应的字段并更新数据列表。
     * 在编辑模式下，一旦完成字段清除，函数会立即返回，不再执行添加模式的逻辑。
     */
    clearData(row, index, type) {
      if (this.id) {
        // 如果是编辑模式
        if (type == 1) {
          // 处理规格相关的字段
          if (this.transfer) {
            // 如果允许互调
            row.spu_name = "";
            row.spu_title = "";
            row.unit = "";
            row.spu_unit = "";
          } else {
            // 如果不允许互调
            row.spu_name = "";
            row.spu_title = "";
          }
        } else {
          // 处理单位相关的字段
          row.spu_unit = "";
          row.unit = "";
        }
        return;
      }
      if (type == 1) {
        // 如果是添加规格
        row.unit = "";
        row.spu_name = "";
        row.spu_name_title = "";
        this.$set(this.formData.dataList, index, row);
        this.$refs.searchSelect.activated = true;
      } else {
        // 如果是添加单位
        row.unit_name = "";
        row.unit = "";
        this.$set(this.formData.dataList, index, row);
        this.$refs.unitSelect.activated = true;
      }
    },
    //不可互调规格搜索
    querySearchAsync(queryString, cb) {
      let spu_list = this.info.attribute;
      let results = queryString
        ? spu_list.filter(this.createFilter(queryString))
        : spu_list;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    // 可互调规格搜索
    spuSearchAsync(queryString, cb) {
      let spu_list = this.info.unit;
      let results = queryString
        ? spu_list.filter(this.createFilter(queryString))
        : spu_list;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //单位搜索
    unitSearchAsync(queryString, cb) {
      let unit_list = this.info.unit;
      let results = queryString
        ? unit_list.filter(this.createFilter(queryString))
        : unit_list;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //过滤方法
    createFilter(queryString) {
      return (restaurant) => {
        // 显式地将restaurant.value转换为字符串，同时处理null和undefined
        const valueAsString = String(restaurant.value || "");
        return (
          valueAsString.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    // 库存设置选择
    edit_inventory(row) {
      this.$set(row, "designated_inventory", row.demo_designated_inventory);
    },
    // 验证输入的值
    blur_input(val) {
      if (!/^-?\d+(\.\d+)?$/.test(val.target.value)) val.target.value = 1;
      if (val.target.value < 0.1 || !val.target.value) {
        val.target.value = 1;
      }
    },
    // SKU设置-加
    plus() {
      this.formData.dataList.push(JSON.parse(JSON.stringify(list)));
      this.inlist.push(JSON.parse(JSON.stringify(list)));
    },
    // SKU设置-减 (添加)
    reduce(index) {
      this.formData.dataList.splice(index, 1);
      this.inlist.splice(index, 1);
    },
    // SKU设置-减 (编辑)
    reduces(index, type) {
      if (type) {
        this.delet(index, 2);
      } else {
        this.formData.dataList.splice(index, 1);
        this.inlist.splice(index, 1);
      }
    },
    // 删除
    delet(index, type) {
      if(this.formData.dataList[index].spu_name==this.purchase_unit){
        this.$message.error("已经设置为统一采购单位，不能删除！")
        return
      }
      let data = packApi({
        id: this.formData.dataList[index].id,
        type: type,
      });
      this.$confirm("此操作将永久删除该单位, 是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          goods_delete(data).then((res) => {
            if (res.errcode == 0) {
              this.formData.dataList.splice(index, 1);
              this.inlist.splice(index, 1);
              this.$message.success("删除成功");
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 校验
    inspect(id) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit("onSubmit", { dataList: this.formData.dataList, id: id });
        }
      });
    },
    // 父组件传来的数据
    setList(list) {
      let dataList = JSON.parse(JSON.stringify(list));
      dataList.forEach((item) => {
        // 如果库存值大于说明是自定义库存
        if (item.designated_inventory > 0) {
          this.$set(item, "demo_designated_inventory", 1);
        } else {
          // 如果designated_inventory没有值,默认就给0
          if (!item.designated_inventory) {
            item.designated_inventory = 0;
          }
          this.$set(
            item,
            "demo_designated_inventory",
            item.designated_inventory
          );
        }
      });
      this.formData.dataList = this._.cloneDeep(dataList);
      this.inlist = this._.cloneDeep(dataList);
    },
    // 判断输入的值是否是数字或小数点
    changePrice(row, key) {
      let value = row[key];
      const regex = /^-?\d+(\.\d{0,2})?$/; // 允许输入负数，最多二位小数
      if (!regex.test(value)) {
        // 如果不符合要求，则从输入中移除非法字符
        value = value.replace(/[^0-9.]/g, ""); // 移除非数字和非小数点的字符
        const parts = value.split("."); // 按小数点分割字符串
        if (parts.length > 2) {
          // 如果小数点超过一个
          value = parts[0] + "." + parts.slice(1).join(""); // 只保留第一个小数点，后面的小数点删除
        } else if (parts.length === 2) {
          // 如果有小数部分
          parts[1] = parts[1].slice(0, 2); // 保留小数部分的前两位数字
          value = parts.join(".");
        }
        row[key] = value;
      } else {
        row[key] = value;
      }
    },
    // 可互调不可互调切换
    changeTransfer(val) {
      // 如果是添加
      if (!this.id) {
        // 根据传入的值确定是可互调（1）还是不可互调（0）
        val = val ? 1 : 0;
        let arr = this.info.unit; // 可互调数组
        let list = this.info.attribute; // 不可互调数组
        this.formData.dataList.forEach((item) => {
          // 如果是可互调状态
          if (val == 1) {
            let info = arr.find((itm) => itm.title == item.spu_name_title);
            // 根据找到的信息更新商品单位和名称
            if (info) {
              item.unit = info.id;
              item.unit_name = info.title;
              item.spu_name = info.id;
              item.spu_name_title = info.title;
            } else {
              // 如果没有找到对应信息，则清空相关字段
              item.unit = "";
              item.unit_name = "";
              item.spu_name = "";
              item.spu_name_title = "";
            }
          } else {
            // 如果是不可互调状态
            let info = list.find((itm) => itm.title == item.spu_name_title);
            let unitInfo = arr.find((itm) => itm.title == item.spu_name_title);
            // 根据找到的信息更新商品单位和名称
            if (info && unitInfo) {
              item.spu_name = info.id;
              item.unit = unitInfo.id;
              item.spu_name_title = info.title;
              item.unit_name = unitInfo.title;
              // 如果没有找到对应信息，则清空相关字段
            } else {
              item.unit = "";
              item.unit_name = "";
              item.spu_name = "";
              item.spu_name_title = "";
            }
          }
        });
        // 如果是编辑
      } else {
        let arr = this.info.unit; // 可互调数组
        let list = this.info.attribute; // 不可互调数组
        val = val ? 1 : 0;
        this.formData.dataList.map((item) => {
          switch (val) {
            // 如果是不可互调状态
            case 0:
              item.is_can = item.spu_name;
              item.spu_name = item.no_can;
              item.spu_title = "";
              item.spu_unit = "";
              // 更新商品标题
              list.forEach((e) => {
                if (e.id == item.spu_name) {
                  item.spu_title = e.title;
                }
              });
              // 更新商品单位
              item.is_unit = item.unit;
              item.unit = item.no_unit;
              arr.forEach((e) => {
                if (e.id == item.unit) {
                  item.spu_unit = e.title;
                }
              });
              break;
            // 如果是可互调状态
            case 1:
              item.no_can = item.spu_name;
              item.spu_name = item.is_can;
              item.spu_title = "";
              item.no_unit = item.unit;
              item.unit = item.is_unit;
              item.spu_unit = "";
              arr.map((c) => {
                if (item.unit == c.id) {
                  item.spu_title = c.title;
                  item.spu_unit = c.title;
                }
              });
              break;
          }
        });
      }
    },
    // 计算？元/基础单位
    dundlePirce(market_price, package_num) {
      if (market_price && package_num) {
        return (market_price / package_num).toFixed(2);
      } else {
        return 0;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.xing::before {
  content: "*";
  color: red;
  position: relative;
  top: 3px;
  margin-right: 5px;
}
.image {
  img {
    width: 15px;
    height: 15px;
  }
}
.form .el-form-item--small.el-form-item {
  margin: 17px 0 !important;
}
/deep/.el-form-item__content {
  display: flex;
  align-items: center;
  .icon {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 10px;
  }
  .span {
    font-size: 14px;
    color: #999999;
  }
}
.note {
  font-size: 12px;
  background-color: #fcfdfd;
  border: 1px solid #e8e8e8;
  padding: 15px 20px;
  border-top: 0;
  box-sizing: border-box;
  color: rgba(0, 0, 0, 0.65);
}
.bundle {
  position: absolute;
  left: 184px;
  top: 27px;
  color: #03a98e;
  font-size: 12px;
}
.spuunit {
  width: 105px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>